/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin;

import org.digitalsoul.switchplugin.patterns.IPattern;
import org.digitalsoul.switchplugin.prefs.Preferences;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

public class FileManager {

    protected final Finder finder;

    public FileManager() {
        finder = new Finder();
    }
    
    private static FileManager instance = new FileManager();
    
    public void switchFile() {
        IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        IEditorPart editor = activePage.getActiveEditor();
        if (editor != null) {
            IEditorInput input = editor.getEditorInput();
            if (input != null) {
                IFile currentFile = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
                switchFile(currentFile);
            }
        }
    }
    
    public void switchFile(IFile currentFile) {
        PatternRing patterns = loadPatterns();
        SwitchFile nextFile = finder.findNextFile(new SwitchFile(currentFile), patterns);
        if (nextFile != null) {
            IFile foundFile = nextFile.getIFile();
            if (foundFile != null && foundFile.exists()) {
                openFileInEditor(foundFile);
            }
        }
    }
    
    public void openFileInEditor(IFile theFile) {
        IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
        try {
            IDE.openEditor(activePage, theFile, true);
        }
        catch (PartInitException e) {
            e.printStackTrace();
        }
    }

    protected PatternRing loadPatterns() {
        
        PatternRing patternRing = new PatternRing();
        for (IPattern pattern : Preferences.loadPatterns()) {
            patternRing.add(pattern);
        }
        return patternRing;
    }
    
    public static FileManager getInstance() {
        return instance;
    }
}
